//操作聊天记录
import {
	openDatabase,
	isOpenDatabase,
	closeDataBase,
	transaction,
	executeSql,
	selectSql
} from "./dbOp.js"
const dataBaseName = 'chat'
const path = 'chatDB'
//判断操作数据库是否打开
function targetDataBaseOpen() {
	return isOpenDatabase(dataBaseName)
}
//打开数据库
function openTargetDB() {
	return openDatabase(dataBaseName, path)
}
//创建指定表
function createTable(tableName) {
	return executeSql({
		name: dataBaseName,
		sql: `create table if not exists "${tableName}"("content" TEXT,"to" TEXT,"from" TEXT,"date" TEXT,"isSelf" TEXT,"type" TEXT)`,
	})
}
//查询指定表所有数据						
function selectSqlAll(tableName) {
	return selectSql({
		name: dataBaseName,
		sql: `select * from "${tableName}"`
	})
}
//为指定表添加数据
function addData(tableName, data) {
	return executeSql({
		name: 'chat',
		sql: `insert into "${tableName}" values('${data.content}','${JSON.stringify(data.to)}','${JSON.stringify(data.from)}','${data.date}','${data.isSelf}','${data.type}')`,
	})
}
//查询数据库中所有表
function queryAllTable() {
	return selectSql({
		name: dataBaseName,
		sql: `select name from sqlite_master where type='table' order by name`
	})
}
//查询指定数据库中指定表的最后一条数据
function queryLastOne(tableName) {
	console.log('查询最后一条数据执行了')
	return selectSql({
		name: dataBaseName,
		sql: `select * from "${tableName}" limit 1 offset (select count(*) - 1  from "${tableName}")`
	})
}

let opChatDataBase = {
	openTargetDB,
	targetDataBaseOpen,
	createTable,
	selectSqlAll,
	addData,
	queryAllTable,
	queryLastOne
}
module.exports = opChatDataBase
